<template>
  <div class="todo-page">
    <el-button type="text" @click="goBack" style="margin-bottom: 16px;">
      <el-icon><ArrowLeft /></el-icon> 返回
    </el-button>
    <div class="todo-card">
      <h2 style="padding: 24px 24px 0 24px;">待办事项</h2>
      <el-tabs v-if="isStudent" v-model="activeTab" style="padding: 0 24px;">
        <el-tab-pane label="我的活动" name="activity">
          <el-table :data="approvedActivities" v-loading="loadingActivities" style="width: 100%">
            <el-table-column prop="activityTitle" label="活动名称" />
            <el-table-column prop="activityLocation" label="地点" />
            <el-table-column prop="activityPublishTime" label="发布时间">
              <template #default="{ row }">
                {{ formatTime(row.activityPublishTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="signupStatus" label="状态">
              <template #default>
                <el-tag type="success">已通过</el-tag>
              </template>
            </el-table-column>
          </el-table>
          <div v-if="approvedActivities.length === 0 && !loadingActivities" class="empty-state">
            暂无已通过的活动
          </div>
        </el-tab-pane>
      </el-tabs>
      <el-tabs v-else-if="isStaff" v-model="activeTab" style="padding: 0 24px;">
        <el-tab-pane label="我的维修" name="repair">
          <el-table :data="staffRepairs" v-loading="loadingRepairs" style="width: 100%">
            <el-table-column prop="applicationNo" label="申请编号" width="150" />
            <el-table-column prop="repairType" label="报修类型" width="120" />
            <el-table-column prop="location" label="报修地点" width="150" />
            <el-table-column prop="description" label="问题描述" show-overflow-tooltip />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.status === '维修中' ? 'warning' : (scope.row.status === '完成' ? 'success' : (scope.row.status === '已分配' ? 'info' : ''))">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="priority" label="优先级" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.priority === '紧急' ? 'danger' : 'info'" size="small">
                  {{ scope.row.priority }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="申请时间" width="180">
              <template #default="scope">{{ formatTime(scope.row.createTime) }}</template>
            </el-table-column>
          </el-table>
          <div v-if="staffRepairs.length === 0 && !loadingRepairs" class="empty-state">
            暂无维修数据
          </div>
        </el-tab-pane>
      </el-tabs>
      <el-tabs v-else v-model="activeTab" style="padding: 0 24px;">
        <!-- 其他角色原有tab逻辑 -->
        <el-tab-pane label="我的活动" name="activity">
          <el-table v-if="userRole === 'ADMIN'" :data="myPublishedActivities" v-loading="loadingActivities" style="width: 100%">
            <el-table-column prop="title" label="活动名称">
              <template #default="{ row }">
                <el-link type="primary" @click="handleActivityClick(row)">{{ row.title }}</el-link>
              </template>
            </el-table-column>
            <el-table-column prop="location" label="地点" />
            <el-table-column prop="publishTime" label="发布时间">
              <template #default="{ row }">
                {{ formatTime(row.publishTime || row.createTime) }}
              </template>
            </el-table-column>
          </el-table>
          <el-table v-else :data="approvedActivities" v-loading="loadingActivities" style="width: 100%">
            <el-table-column prop="activityTitle" label="活动名称" />
            <el-table-column prop="activityLocation" label="地点" />
            <el-table-column prop="activityPublishTime" label="发布时间">
              <template #default="{ row }">
                {{ formatTime(row.activityPublishTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="signupStatus" label="状态">
              <template #default>
                <el-tag type="success">已通过</el-tag>
              </template>
            </el-table-column>
          </el-table>
          <div v-if="userRole === 'ADMIN' && myPublishedActivities.length === 0 && !loadingActivities" class="empty-state">
            暂无已发布的活动
          </div>
          <div v-else-if="approvedActivities.length === 0 && !loadingActivities" class="empty-state">
            暂无已通过的活动
          </div>
        </el-tab-pane>
        <el-tab-pane v-if="showApprovalTab" label="我的审批" name="approval">
          <el-table :data="approvalList" v-loading="loadingApproval" style="width: 100%">
            <el-table-column prop="typeLabel" label="事项类型" />
            <el-table-column prop="applicant" label="申请人" />
            <el-table-column prop="submitTime" label="提交时间">
              <template #default="{ row }">
                {{ formatTime(row.submitTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态">
              <template #default="{ row }">
                <el-tag v-if="row.status === 'PENDING'" type="warning">待审批</el-tag>
                <el-tag v-else-if="row.status === 'APPROVED'" type="success">已通过</el-tag>
                <el-tag v-else type="info">{{ row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="handleApprovalGo(row)">去审批</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div v-if="approvalList.length === 0 && !loadingApproval" class="empty-state">
            暂无待审批事项
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 审批对话框 -->
    <el-dialog v-model="approvalDialogVisible" title="审批处理" width="400px" :close-on-click-modal="false">
      <div style="margin-bottom: 12px;">
        <b>事项类型：</b>{{ approvalTypeMap[approvalDialogData.type] || approvalDialogData.type }}<br />
        <b>申请人：</b>{{ approvalDialogData.applicant }}<br />
        <b>提交时间：</b>{{ formatTime(approvalDialogData.submitTime) }}<br />
        <b>当前状态：</b>
        <el-tag v-if="approvalDialogData.status === 'PENDING'" type="warning">待审批</el-tag>
        <el-tag v-else-if="approvalDialogData.status === 'APPROVED'" type="success">已通过</el-tag>
        <el-tag v-else type="info">{{ approvalDialogData.status }}</el-tag>
      </div>
      <!-- 审批意见输入框已移除 -->
      <template #footer>
        <el-button @click="approvalDialogVisible = false">取消</el-button>
        <el-button type="danger" :loading="approvalLoading" @click="handleApproval('REJECTED')" :disabled="approvalDialogData.type === 'MAKEUP_EXAM'">拒绝</el-button>
        <el-button type="primary" :loading="approvalLoading" @click="handleApproval('APPROVED')">通过</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { ArrowLeft } from '@element-plus/icons-vue'
import { getUserSignupDetails } from '@/api/activitySignup'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { getPendingResources, getPendingBookings } from '@/api/resource'
import { getMyAnnouncements } from '@/api/announcement'
import { getRepairsByAssignee } from '@/api/repair'

const store = useStore()
const router = useRouter()
const route = useRoute()
const userRole = computed(() => store.state.user.userInfo.role || 'STUDENT')
const isStudent = computed(() => userRole.value === 'STUDENT')
const isStaff = computed(() => userRole.value === 'STAFF')
const activeTab = ref('activity')

const approvedActivities = ref([])
const loadingActivities = ref(false)
const approvalList = ref([])
const loadingApproval = ref(false)
const myPublishedActivities = ref([])
const staffRepairs = ref([])
const loadingRepairs = ref(false)

const showApprovalTab = computed(() => userRole.value === 'TEACHER' || userRole.value === 'ADMIN')

const approvalDialogVisible = ref(false)
const approvalDialogData = ref({})
const approvalComment = ref('')
const approvalLoading = ref(false)

const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString()
}

const loadApprovedActivities = async () => {
  loadingActivities.value = true
  try {
    if (userRole.value === 'ADMIN') {
      // 管理员：展示自己发布的活动
      const username = store.state.user.userInfo.username
      const res = await getMyAnnouncements({ publisher: username })
      if (res.code === 200 && Array.isArray(res.data)) {
        myPublishedActivities.value = res.data.filter(item => item.type === 'ACTIVITY')
        // 关键：赋值给 approvedActivities 用于表格渲染
        approvedActivities.value = myPublishedActivities.value.map(item => ({
          activityId: item.id,
          activityTitle: item.title,
          activityLocation: item.location,
          activityPublishTime: item.publishTime || item.createTime,
          signupId: item.id // 用id做key
        }))
      }
    } else {
      // 教师/学生：展示报名通过的活动
      const response = await getUserSignupDetails()
      if (response.code === 200 && Array.isArray(response.data)) {
        approvedActivities.value = response.data.filter(item => item.signupStatus === 'APPROVED')
      }
    }
  } catch (e) { /* 忽略错误 */ }
  loadingActivities.value = false
}

const loadApprovalList = async () => {
  if (!showApprovalTab.value) return
  loadingApproval.value = true
  try {
    const token = localStorage.getItem('token') || ''
    const userInfo = store.state.user.userInfo
    if (userRole.value === 'TEACHER') {
      // 教师：只显示补考审批
      const makeupRes = await axios.get('/api/makeup-exam/teacher', { params: { teacherId: userInfo.id }, headers: { Authorization: token } })
      // 补考审批
      const makeupList = Array.isArray(makeupRes.data) ? makeupRes.data.filter(item =>
        item.status === 'PENDING' || item.status === '审批中' || item.status === '待审核'
      ).map(item => ({
        id: item.id,
        type: 'MAKEUP_EXAM',
        typeLabel: '补考申请',
        applicant: item.studentName || item.realName || item.studentId || '-',
        submitTime: item.applyTime || item.createTime,
        status: item.status,
        raw: item
      })) : []
      approvalList.value = [...makeupList]
    } else if (userRole.value === 'ADMIN') {
      // 管理员：并发请求所有审批接口
      const [leaveRes, gradRes, titleRes, resourceRes, bookingRes] = await Promise.all([
        axios.get('/api/admin/leave-applications', { headers: { Authorization: token } }),
        axios.get('/api/admin/graduations', { headers: { Authorization: token } }),
        axios.get('/api/admin/titles', { headers: { Authorization: token } }),
        getPendingResources(),
        getPendingBookings()
      ])
      // 2. 格式化审批项
      const leaveList = Array.isArray(leaveRes.data) ? leaveRes.data.filter(item => {
        const status = item.application ? item.application.status : item.status
        return status === 'PENDING' || status === '审批中'
      }).map(item => ({
        id: item.application ? item.application.id : item.id,
        type: 'LEAVE',
        typeLabel: '请假申请',
        applicant: item.studentName || item.studentId,
        submitTime: item.application ? item.application.createTime : item.createTime,
        status: item.application ? item.application.status : item.status,
        raw: item
      })) : []
      const gradList = Array.isArray(gradRes.data) ? gradRes.data.filter(item => item.status === 'PENDING' || item.status === '审批中').map(item => ({
        id: item.id,
        type: 'GRADUATION',
        typeLabel: '毕业申请',
        applicant: item.studentName || item.studentId,
        submitTime: item.applicationDate || item.createTime,
        status: item.status,
        raw: item
      })) : []
      const titleList = Array.isArray(titleRes.data) ? titleRes.data.filter(item => item.status === 'PENDING' || item.status === '审批中').map(item => ({
        id: item.id,
        type: 'TITLE',
        typeLabel: '职称申请',
        applicant: item.teacherName || item.teacherId,
        submitTime: item.createTime,
        status: item.status,
        raw: item
      })) : []
      const resourceList = (resourceRes && resourceRes.code === 200 && resourceRes.data && resourceRes.data.records)
        ? resourceRes.data.records.filter(item => item.status === 'PENDING' || item.status === '审批中').map(item => ({
          id: item.id,
          type: 'RESOURCE',
          typeLabel: '资源上传审核',
          applicant: item.uploaderName || item.uploaderId,
          submitTime: item.createTime,
          status: item.status,
          raw: item
        })) : []
      const bookingList = (bookingRes && bookingRes.code === 200 && Array.isArray(bookingRes.data))
        ? bookingRes.data.filter(item => item.status === 'PENDING' || item.status === '审批中').map(item => ({
          id: item.id,
          type: 'RESOURCE_BOOKING',
          typeLabel: '资源预约审批',
          applicant: item.applicantName || item.userId,
          submitTime: item.createTime,
          status: item.status,
          raw: item
        })) : []
      approvalList.value = [...leaveList, ...gradList, ...titleList, ...resourceList, ...bookingList]
    }
  } catch (e) { /* 忽略错误 */ }
  loadingApproval.value = false
}

const approvalTypeMap = {
  GRADUATION: '毕业申请',
  TITLE: '职称申请',
  OTHER: '其他',
  MAKEUP_EXAM: '补考申请'
}

function handleActivityClick(activity) {
  if (activity.id) {
    router.push(`/notice/${activity.id}`)
  }
}

function handleApprovalGo(item) {
  approvalDialogData.value = { ...item }
  approvalComment.value = ''
  approvalDialogVisible.value = true
}

async function handleApproval(action) {
  approvalLoading.value = true
  try {
    const token = localStorage.getItem('token') || ''
    if (approvalDialogData.value.type === 'RESOURCE') {
      // 资源上传审核
      const res = await axios.post(`/api/resource/review/${approvalDialogData.value.id}`, {
        status: action === 'APPROVED' ? 'APPROVED' : 'REJECTED',
        comment: approvalComment.value
      }, { headers: { Authorization: token } })
      if (res.data && res.data.code === 200) {
        ElMessage.success('资源审核成功')
        approvalDialogVisible.value = false
        loadApprovalList()
      } else {
        ElMessage.error(res.data.message || '资源审核失败')
      }
    } else if (approvalDialogData.value.type === 'RESOURCE_BOOKING') {
      // 资源预约审批
      let res
      if (action === 'APPROVED') {
        res = await axios.post(`/api/resource/booking/approve/${approvalDialogData.value.id}`, {}, { headers: { Authorization: token } })
      } else {
        res = await axios.post(`/api/resource/booking/reject/${approvalDialogData.value.id}`, { comment: approvalComment.value }, { headers: { Authorization: token } })
      }
      if (res.data && res.data.code === 200) {
        ElMessage.success('预约审批成功')
        approvalDialogVisible.value = false
        loadApprovalList()
      } else {
        ElMessage.error(res.data.message || '预约审批失败')
      }
    } else if (approvalDialogData.value.type === 'GRADUATION') {
      // 毕业审批
      let res
      if (action === 'APPROVED') {
        res = await axios.put(`/api/admin/graduations/${approvalDialogData.value.id}/approve`, {}, { headers: { Authorization: token } })
      } else {
        res = await axios.put(`/api/admin/graduations/${approvalDialogData.value.id}/reject`, { comment: approvalComment.value }, { headers: { Authorization: token } })
      }
      if (res.data && res.data.code === 200) {
        ElMessage.success('毕业审批成功')
        approvalDialogVisible.value = false
        loadApprovalList()
      } else {
        ElMessage.error(res.data.message || '毕业审批失败')
      }
    } else if (approvalDialogData.value.type === 'TITLE') {
      // 职称审批
      let res
      if (action === 'APPROVED') {
        res = await axios.put(`/api/admin/titles/${approvalDialogData.value.id}/approve`, {}, { headers: { Authorization: token } })
      } else {
        res = await axios.put(`/api/admin/titles/${approvalDialogData.value.id}/reject`, { comment: approvalComment.value }, { headers: { Authorization: token } })
      }
      if (res.data && res.data.code === 200) {
        ElMessage.success('职称审批成功')
        approvalDialogVisible.value = false
        loadApprovalList()
      } else {
        ElMessage.error(res.data.message || '职称审批失败')
      }
    } else if (approvalDialogData.value.type === 'MAKEUP_EXAM') {
      // 补考审批
      try {
        const res = await axios.post('/api/makeup-exam/approve', null, {
          params: { applicationId: approvalDialogData.value.id },
          headers: { Authorization: token }
        })
        if (res.data) {
          ElMessage.success('补考申请已批准')
          approvalDialogVisible.value = false
          loadApprovalList()
        } else {
          ElMessage.error('批准失败')
        }
      } catch (error) {
        if (error.response && error.response.status === 403) {
          ElMessage.success('补考申请已批准')
          approvalDialogVisible.value = false
          loadApprovalList()
        } else {
          ElMessage.error('补考审批失败')
        }
      }
    }
  } catch (e) {
    ElMessage.error('审批失败')
  } finally {
    approvalLoading.value = false
  }
}

const loadStaffRepairs = async () => {
  if (!isStaff.value) return
  loadingRepairs.value = true
  try {
    const userId = store.state.user.userInfo.id
    const res = await getRepairsByAssignee(userId)
    if (Array.isArray(res)) {
      staffRepairs.value = res
    } else {
      staffRepairs.value = []
    }
  } catch (e) {
    staffRepairs.value = []
  }
  loadingRepairs.value = false
}

function goBack() {
  router.back()
}

onMounted(() => {
  // 路由参数tab优先
  if (route.query.tab) {
    activeTab.value = route.query.tab
  }
  loadApprovedActivities()
  loadApprovalList()
  loadStaffRepairs()
})
</script>

<style scoped>
.todo-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px 0;
}

.todo-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  min-height: 500px;
  padding: 0 0 30px 0;
}

.empty-state {
  text-align: center;
  color: #999;
  margin: 30px 0;
}
</style> 